package com.itany.shop.servlet;


import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author 石小俊
 */
@WebServlet("*.code")
public class CodeServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getServletPath();
        switch (path) {
            case "/show.code":
                showCode(request, response);
                break;
        }
    }

    public void showCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1.在内存中创建一个画板
        BufferedImage image = new BufferedImage(50, 25, BufferedImage.TYPE_INT_RGB);
        // 2.获取画笔
        Graphics graphics = image.getGraphics();
        // 3.设置画笔填充的矩形区域
        graphics.fillRect(0, 0, 50, 25);
        // 4.设置字体与颜色
        graphics.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 18));
        // 随机色
        Random random = new Random();
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // 绘制图片内容
//        char c = (char)(Math.random() * ('z' - 'a' + 1) + 'a')
//        int i = (int)(Math.random() * (9-0+1) + 0)
        // 定义一个字符串,该字符串中存储了所有可能在验证码中展示的字符
        String s = "0123456789qwertyuioplkjhgfdaszxcvbnm";
        // 随机获取四位字符
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        String code = buffer.toString();
        System.out.println("验证码:" + code);
        // 为了便于校验,可以将验证码的内容存储在session中
        request.getSession().setAttribute("code", code);
        // 将验证码内容绘制到图片中
        graphics.drawString(code, 5, 18);
        // 输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

}
